package com.suixun.service;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.suixun.dao.SysConfigMapper;
import com.suixun.entity.SysConfig;
import com.suixun.service.redis.RedisService;

/**
 * Constants.java
 * 
 * 定义的一些会用的常量
 * 
 * @author <a href="mailto:huangy@17find.com">hellmash</a>
 * @version create on 2015-07-20 10:31
 *          <p>
 *          CopyRight(c)2015 杭州随寻科技有限公司 17find.com 版权所有
 */
public class Constants {

	// http 相关
	public final static String CONTENT_TYPE_JSON = "application/json";
	public final static String CACHE_CONTROL = "Cache-Control";
	public final static String NO_CACHE = "no-store";
	public final static String ACCESS_TOKEN = "access_token";
	public final static String TOKEN_TYPE = "token_type";
	public final static String TOKEN_SCOPE = "token_scope";
	public final static String EXPIRES_IN = "expires_in";
	public final static String GET = "GET";
	public final static String POST = "POST";
	public final static String PUT = "PUT";
	public final static String DELETE = "DELETE";
	public final static String AUTHORIZATION = "Authorization";
	public final static String API_DB = "api";
	public final static long TOKEN_TIMEOUT = 6000l;
	public final static String CONSUMER_KEY = "consumer_key";
	public final static String CONSUMER_SECRET = "consumer_secret";
	public final static String OAUTH_TOKEN = "oauth_token";
	public final static String TOKEN_ALL_SCOPE = "all";
	public final static String TOKEN_READONLY_SCOPE = "readonly";
	public static final String TOKEN_JAVASCRIPT_SCOPE = "js";

	// restful资源名称
	public final static String DEFAULT_RESOURCE_NAME = "resource";
	public final static String TOKEN_RESOURCE_NAME = "token";
	public final static String TOKEN_HEADER_NAME = "X-Auth-Token";
	public final static String CONSUMER_RESOURCE_NAME = "consumer";
	public final static String ERROR_RESOURCE_NAME = "error";
	public final static String USER_RESOURCE_NAME = "user";
	public final static String USERS_RESOURCE_NAME = "users";
	// 7 * 24 * 60 * 60 * 1000 * 10 70天
	public final static long TOKEN_EXPMILLIS = 604800000l * 10l;

	// URL查询参数
	public final static String URL_LIMIT = "limit";
	public final static String URL_FULL = "full";
	public final static String URL_KEYWORD = "keyword";
	public static final int NO_TRUST_DIMENSION = -1;
	public static final String URL_ATTR_DIMENSION = "dimension";
	public static final String URL_ATTR_DIMENSIONS = "dimensions";
	public static final String URL_NAME = "name";
	public static final String URL_SORT = "sort";
	public static final String URL_TYPE = "type";
	public static final String URL_ALGORITHMS = "algorithms";

	// 排序字段
	public final static String SORT_ID = "id";
	public final static String SORT_NAME = "name";
	public final static String SORT_DATE = "date";

	// 用户相关
	public final static int DEFAULT_USER_TYPE = 1;
	public final static String DEFAULT_BABY_NAME = "宝宝";

	// 字段类型
	public final static String TYPE_VARCHAR = "VARCHAR";
	public final static String TYPE_INT = "INT";
	public final static String TYPE_BIGINT = "BIGINT";
	public final static String TYPE_DOUBLE = "DOUBLE";
	public final static String TYPE_TEXT = "TEXT";
	public final static String TYPE_DATETIME = "DATETIME";
	public final static String TYPE_BOOLEAN = "BOOLEAN";
	public final static String TYPE_ENUM = "ENUM";

	// LOG
	public final static int LIST_LOG_LIMIT = 10;

	public static final Long ANONYMOUS_USER = -1L;

	public static String DEFAULT_CLIENT = "default_client";

	// alarm
	public static Integer ALARM_POWER_TYPE = 20;
	public static Integer ALARM_LOW_POWERVALUE = 1; // 1 2 3 4

	// media
	public static String MEDIA_HTTP_URL = "http://api.17find.com/media";
	public static Integer MEDIA_MAX_SIZE = 1024 * 1024 * 5; // 5M
	public static String[] MEDIA_FILE_EXTS = { "gif", "png", "jpeg", "jpg", "mp3", "amr", "wav", "awb" };

	// 信鸽
	public static long ANDROID_ACCESS_ID = 2100139658;
	public static String ANDROID_SECRET_KEY = "9dd8882865f841b054966a01c1531348";
	public static long IOS_ACCESS_ID = 2200139659l;
	public static String IOS_SECRET_KEY = "1553adb364340cc5a28b54db6f15b346";

	private static String PLATFORM_ENV = "DEV";
	public static HashMap<String, String> THIRD_PARTY_RESOURCES = null;

	/**
	 * 字符编码集
	 */
	public static final String CHARSET = "UTF-8";

	/**
	 * openapi的请求地址 <br>
	 * 联调环境为：{@link http://openapi.yijifu.net/gateway.html} <br>
	 * 生产环境为：{@link http://openapi.yiji.com/gateway.html}
	 */
	private static String OPENAPI_ADDRESS = "http://openapi.yiji.com/gateway.html";
	// public static final String OPENAPI_ADDRESS =
	// "http://openapi.yijifu.net/gateway.html";
	private static String PARTNER_ID = "20150728020006819799";
	// public static final String PARTNER_ID = "20150818020000465881";
	private static String SERCURITY_KEY = "110da187fde04facf3dbab101ffd8abd";
	// public static final String SERCURITY_KEY =
	// "311d75105cf8fb3212ddb479bd2f1aa1";
	private static String SERVICE_CODE = "BILL_PAYMENT";
	// public static final String SERVICE_CODE = "PUBLIC_HOUSING";
	private static String NOTIFY_URL = "http://api.17find.com/yiji/notify";
	// public static String NOTIFY_URL =
	// "http://222.46.27.218:8800/yiji/notify";
	private static String YIJIPAY_ENV = "PROD";
	private static String RENEWALFEES_OKURL = "http://www.17find.com/xufei/notify";
	private static String RESERVE_OKURL = "http://www.17find.com/book/notify";
	private static String RESUMBIT_OKURL = "http://www.17find.com/buka/notify";
	private static String OPENAPI_ADDRESS_WEB = "https://openapi.yijifu.net/gateway";
	private static String OPENAPI_ADDRESS_WEB2 = "https://mpay.yijifu.net/cashier/startPay.html";
	private static String PARTNER_ID_WEB = "20140411020055684571";
	private static String SERCURITY_KEY_WEB = "c9cef22553af973d4b04a012f9cb8ea8";
	private static String JXT_PATH;

	/**
	 * fastPayTradeRefund的请求地址 <br>
	 * 联调环境为：{@link https://openapi.yijifu.net/gateway.html} <br>
	 * 生产环境为：{@link https://api.yiji.com}
	 */
	private static String OP_NOTIFY_URL = "http://oss.17find.com:8090/yiji/notify";
	public final static String OP_REFUND_SERVICE = "fastPayTradeRefund";

	private static SysConfigMapper sysConfigMapper;
	private static RedisService redisService;
	private final static Logger logger = LoggerFactory.getLogger(Constants.class);

	static {

		WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext();
		sysConfigMapper = (SysConfigMapper) wac.getBean("sysConfigMapper");
		redisService = (RedisService) wac.getBean("redisService");

		Properties prop = new Properties();
		String path = Constants.class.getClassLoader().getResource("webconfig.properties").getPath();
		try {
			InputStream is = new FileInputStream(path);
			prop.load(is);
			if (prop.getProperty("PLATFORM_ENV") != null)
				PLATFORM_ENV = prop.getProperty("PLATFORM_ENV").trim();

			ObjectMapper mapper = new ObjectMapper();
			mapper.getFactory().configure(JsonGenerator.Feature.ESCAPE_NON_ASCII, true);

			if (prop.getProperty("THIRD_PARTY_RESOURCES") != null)
				THIRD_PARTY_RESOURCES = mapper.readValue(prop.getProperty("THIRD_PARTY_RESOURCES").trim(),
						HashMap.class);

			if (prop.getProperty("MEDIA_HTTP_URL") != null)
				MEDIA_HTTP_URL = prop.getProperty("MEDIA_HTTP_URL").trim();
			if (prop.getProperty("OPENAPI_ADDRESS") != null)
				OPENAPI_ADDRESS = prop.getProperty("OPENAPI_ADDRESS").trim();
			if (prop.getProperty("PARTNER_ID") != null)
				PARTNER_ID = prop.getProperty("PARTNER_ID").trim();
			if (prop.getProperty("SERCURITY_KEY") != null)
				SERCURITY_KEY = prop.getProperty("SERCURITY_KEY").trim();
			if (prop.getProperty("SERVICE_CODE") != null)
				SERVICE_CODE = prop.getProperty("SERVICE_CODE").trim();
			if (prop.getProperty("YIJIPAY_ENV") != null)
				YIJIPAY_ENV = prop.getProperty("YIJIPAY_ENV").trim();
			if (prop.getProperty("NOTIFY_URL") != null)
				NOTIFY_URL = prop.getProperty("NOTIFY_URL").trim();
			if (prop.getProperty("RENEWALFEES_OKURL") != null)
				RENEWALFEES_OKURL = prop.getProperty("RENEWALFEES_OKURL").trim();
			if (prop.getProperty("RESERVE_OKURL") != null)
				RESERVE_OKURL = prop.getProperty("RESERVE_OKURL").trim();
			if (prop.getProperty("RESUMBIT_OKURL") != null)
				RESUMBIT_OKURL = prop.getProperty("RESUMBIT_OKURL").trim();
			if (prop.getProperty("OPENAPI_ADDRESS_WEB") != null)
				OPENAPI_ADDRESS_WEB = prop.getProperty("OPENAPI_ADDRESS_WEB").trim();
			if (prop.getProperty("OPENAPI_ADDRESS_WEB2") != null)
				OPENAPI_ADDRESS_WEB2 = prop.getProperty("OPENAPI_ADDRESS_WEB2").trim();
			if (prop.getProperty("PARTNER_ID_WEB") != null)
				PARTNER_ID_WEB = prop.getProperty("PARTNER_ID_WEB").trim();
			if (prop.getProperty("SERCURITY_KEY_WEB") != null)
				SERCURITY_KEY_WEB = prop.getProperty("SERCURITY_KEY_WEB").trim();
			if (prop.getProperty("OP_NOTIFY_URL") != null)
				OP_NOTIFY_URL = prop.getProperty("OP_NOTIFY_URL").trim();
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
	}

	public static String getJxtPath() {

		if (StringUtils.isNotBlank(JXT_PATH)) {
			return JXT_PATH;
		}
		Properties prop = new Properties();
		String path = Constants.class.getClassLoader().getResource("webconfig.properties").getPath();
		try {
			InputStream is = new FileInputStream(path);
			prop.load(is);
		} catch (Exception e) {
			return JXT_PATH;
		}

		JXT_PATH = prop.getProperty("JXT_URL").trim();
		return JXT_PATH;
	}

	public static Map<String, List<BigDecimal>> RENEWAL_DEVICE_PRICES() {
		Map<String, List<BigDecimal>> rtn = (Map<String, List<BigDecimal>>) redisService.get("RENEWAL_DEVICE_PRICES");
		if (rtn != null)
			return rtn;
		SysConfig sysConfig = sysConfigMapper.selectByPrimaryKey("RENEWAL_DEVICE_PRICES");
		if (sysConfig != null) {
			ObjectMapper mapper = new ObjectMapper();
			try {
				rtn = mapper.readValue(sysConfig.getValue().trim(), new HashMap<String, List<BigDecimal>>().getClass());
				redisService.put("RENEWAL_DEVICE_PRICES", rtn);
				return rtn;
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return null;
	}

	public static BigDecimal[] RENEWAL_PACKAGE_FEES() {
		BigDecimal[] rtn = (BigDecimal[]) redisService.get("RENEWAL_PACKAGE_FEES");
		if (rtn != null)
			return rtn;
		SysConfig sysConfig = sysConfigMapper.selectByPrimaryKey("RENEWAL_PACKAGE_FEES");
		if (sysConfig != null) {
			ObjectMapper mapper = new ObjectMapper();
			try {
				rtn = mapper.readValue(sysConfig.getValue().trim(), BigDecimal[].class);
				redisService.put("RENEWAL_PACKAGE_FEES", rtn);
				return rtn;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return null;
	}

	public static HashMap<String, BigDecimal> PURCHASE_DEVICE_PRICES() {
		HashMap<String, BigDecimal> rtn = (HashMap<String, BigDecimal>) redisService.get("PURCHASE_DEVICE_PRICES");
		if (rtn != null)
			return rtn;
		SysConfig sysConfig = sysConfigMapper.selectByPrimaryKey("PURCHASE_DEVICE_PRICES");
		if (sysConfig != null) {
			ObjectMapper mapper = new ObjectMapper();
			try {
				rtn = new HashMap<String, BigDecimal>();
				HashMap<String, Double> data = mapper.readValue(sysConfig.getValue().trim(), HashMap.class);
				for (String key : data.keySet()) {
					rtn.put(key, new BigDecimal(String.valueOf(data.get(key))));
				}
				redisService.put("PURCHASE_DEVICE_PRICES", rtn);
				return rtn;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return null;
	}

	public static String get_platform_env() {
		return PLATFORM_ENV;
	}

	public static String getMediaSavePath() throws IOException {
		String mediapath = "";
		Properties prop = new Properties();
		String path = Constants.class.getClassLoader().getResource("webconfig.properties").getPath();
		InputStream is = new FileInputStream(path);
		prop.load(is);
		mediapath = prop.getProperty("media.savepath").trim();
		return mediapath;
	}

	/*
	 * 获取付款方ID
	 */
	public static String get_payerId(String holdname) {
		if (holdname != null) {
			if (holdname.equals("道有道")) {
				return "20150929020008248616";
			}
			if (holdname.equals("道有道2")) {
				return "20150930020000571664";
			}
		}
		return "";
	}

	/**
	 * 异步通知URL，当服务为异步服务时会将最终结果发送至该地址 具体请见开发文档
	 */
	public static String getBankcode(String bankname) {
		String bankcode = "";
		if (bankname.contains("中国建设银行")) {
			bankcode = "CCB";
		} else if (bankname.contains("中国农业银行")) {
			bankcode = "ABC";
		} else if (bankname.contains("中国光大银行")) {
			bankcode = "CEB";
		} else if (bankname.contains("民生银行")) {
			bankcode = "CMBC";
		} else if (bankname.contains("中信银行")) {
			bankcode = "CITIC";
		} else if (bankname.contains("重庆农村商业银行")) {
			bankcode = "CQRCB";
		} else if (bankname.contains("兴业银行")) {
			bankcode = "CIB";
		} else if (bankname.contains("中国工商银行")) {
			bankcode = "ICBC";
		} else if (bankname.contains("招商银行")) {
			bankcode = "CMB";
		} else if (bankname.contains("中国邮政储蓄银行")) {
			bankcode = "PSBC";
		} else if (bankname.contains("浦发银行")) {
			bankcode = "SPDB";
		} else if (bankname.contains("平安银行")) {
			bankcode = "PINGANBK";
		} else if (bankname.contains("交通银行")) {
			bankcode = "COMM";
		} else if (bankname.contains("华夏银行")) {
			bankcode = "HXB";
		} else if (bankname.contains("中国银行")) {
			bankcode = "BOC";
		}
		return bankcode;
	}

	public static String get_openapi_address() {
		return OPENAPI_ADDRESS;
	}

	public static String get_partner_id() {
		return PARTNER_ID;
	}

	public static String get_sercurity_key() {
		return SERCURITY_KEY;
	}

	public static String get_service_code() {
		return SERVICE_CODE;
	}

	public static String get_yijipay_env() {
		return YIJIPAY_ENV;
	}

	public static String get_notify_url() {
		return NOTIFY_URL;
	}

	public static String get_op_notify_url() {
		return OP_NOTIFY_URL;
	}

	/*
	 * 获取续费成功URL
	 */
	public static String get_renewalfees_okurl() {
		return RENEWALFEES_OKURL;
	}

	public static String get_reserve_okurl() {
		return RESERVE_OKURL;
	}

	public static String get_resumbit_okurl() {
		return RESUMBIT_OKURL;
	}

	public static String get_openapi_address_web() {
		return OPENAPI_ADDRESS_WEB;
	}

	public static String get_openapi_address_web2() {
		return OPENAPI_ADDRESS_WEB2;
	}

	public static String get_partner_id_web() {
		return PARTNER_ID_WEB;
	}

	public static String get_sercurity_key_web() {
		return SERCURITY_KEY_WEB;
	}

	/**
	 * 请求协议，建议使用httpPost
	 */
	public static final String HTTP_POST_PROTOCOL = "httpPost";

	/**
	 * 签名类型，支持：<br>
	 * SHA-256 <br>
	 * MD5
	 */
	public static final String SIGN_TYPE = "MD5";

	/**
	 * 返回URL，当服务为跳转服务时同步通知到该地址。 具体请见开发文档
	 */
	public static final String RETURN_URL = "";

}
